#include <stdio.h>
#include <string.h>
#include "dl.h"

func_cache_t func_cache;

int prefix_check(const char *s1, const char *prefix)
{
    return memcmp(s1, prefix, strlen(prefix));
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        return -1;
    }

    FILE *f = fopen(argv[1], "r");
    if (!f) {
        printf("Fail to open file %s\n", argv[1]);
        return -2;
    }
    char s[1024];
    while (fgets(s, sizeof(s), f)) {
        if (s[0] == '#') continue;
        s[strlen(s) - 2] = 0;
        if (prefix_check(s, "echo") == 0) {
            printf("%s\n", s + 6); 
        } else if (prefix_check(s, "t=") == 0) {
            char *cmd = s + 4;
            char *h1 = strstr(cmd, ");");
            h1[0] = 0;
            h1 += 8;
            char fname[256];
            char *cache = func_cache.get_func(cmd);
            if (cache) {
                strcpy(fname, cache);
            } else {
                FILE *fp = popen(cmd, "r");
                if (fp) {
                    char t[256];
                    if (fgets(t, sizeof(t), fp)) {
                        t[strlen(t) - 2] = 0;
                        strcpy(fname, t + 42);
                        func_cache.new_func(cmd, fname);
                    }
                    pclose(fp);
                } else {
                    strcpy(fname, "Error");
                    printf("Error\n");
                }
            }
            char *h2 = strstr(h1, "${t:42:-1}");
            h2[0] = 0;
            h2 += 10;
            printf("%s%s%s\n", h1, fname, h2);
        }
    }
    return 0;
}
